import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class TcpEchoServer1 {
    ServerSocket socket = null;

    //在构造对象的时候，绑定端口号
    public TcpEchoServer1(int port) throws IOException {
        socket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        ExecutorService executorService = Executors.newCachedThreadPool();

        //与客户端建立连接，接收多个连接
        while (true){
            Socket clientSocket = socket.accept();

            //处理请求
            /*Thread thread = new Thread(() -> {
                processConnection(clientSocket);
            });
            thread.start();*/

            executorService.submit(() -> {
                processConnection(clientSocket);
            });
        }
    }

    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s:%d] 客户端上线",clientSocket.getInetAddress(),clientSocket.getPort());

        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);

            //接收多个请求
            while (true){
                if (!scanner.hasNext()){
                    System.out.printf("[%s:%d]客户端下线",clientSocket.getInetAddress(),clientSocket.getPort());
                    return;
                }
                //服务器接收客户端请求三个步骤
                //1.接收请求并解析
                String request = scanner.next();
                //2.根据请求，计算响应
                String response = process(request);
                //3.返回响应到客户端
                printWriter.println(response);
                printWriter.flush();
                //4.打印日志
                System.out.printf("[%s:%d] req:%s resp:%s\n",clientSocket.getInetAddress(),
                        clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String process(String request) {
        return  request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer1 tcpEchoServer1 = new TcpEchoServer1(9090);
        tcpEchoServer1.start();
    }
}
